package com.yxy.chatserver.handler;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yxy.chatserver.domain.po.BaseMessage;
import com.yxy.chatserver.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.time.LocalDateTime;

/**
 * 消息处理
 */
@Component
@Slf4j
public class MessageWebSocketHandler {

    @Autowired
    private Gson gson;

    @Autowired
    private WebSocketManager webSocketManager;

    @Autowired
    private MessageService messageService;

    /**
     * 处理消息
     * @param session
     * @param jsonObject
     * @param fromUserId
     * @throws Exception
     */
    public void handleMessage(WebSocketSession session, JsonObject jsonObject, String fromUserId) throws Exception{
        // 获取消息类型
        String type = jsonObject.get("type").getAsString();
        switch (type){
            case "text":
                handleText(session, jsonObject, fromUserId);
                break;
            case "image":
                handleImage(session, jsonObject, fromUserId);
                break;
            case "file":
                handleFile(session, jsonObject, fromUserId);
                break;
        }
    }

    /**
     * 处理文本消息
     * @param session
     * @param jsonObject
     * @param fromUserId
     * @throws Exception
     */
    private void handleText(WebSocketSession session, JsonObject jsonObject, String fromUserId) throws Exception {
        BaseMessage msg = gson.fromJson(jsonObject, BaseMessage.class);
        msg.setFromUserId(fromUserId);

        if (msg.getSendTime() == null) {
            msg.setSendTime(LocalDateTime.now());
        }

        msg.setStatus("sent");

        // 获取接收者的会话
        WebSocketSession toSession = webSocketManager.getSessionByUserId(msg.getToUserId());

        // 将消息转换为JSON字符串
        String msgJson = gson.toJson(msg);
        TextMessage textMessage = new TextMessage(msgJson);

        // 如果接收者在线，直接发送消息
        if (toSession != null && toSession.isOpen()) {
            toSession.sendMessage(textMessage);
            msg.setStatus("delivered");
            log.info("✅ 消息已送达用户：{}", msg.getToUserId());
        } else {
            // 如果接收者不在线，保存消息
            log.info("⏳ 用户 {} 不在线，消息已保存", msg.getToUserId());
            messageService.saveMessage(msg);
        }
        // 发送消息状态回执给发送者
        String statusJson = gson.toJson(msg);
        session.sendMessage(new TextMessage(statusJson));
    }

    /**
     * 处理文件
     * @param session
     * @param jsonObject
     * @param fromUserId
     */
    private void handleFile(WebSocketSession session, JsonObject jsonObject, String fromUserId) {
    }

    /**
     * 处理图片消息
     * @param session
     * @param jsonObject
     * @param fromUserId
     */
    private void handleImage(WebSocketSession session, JsonObject jsonObject, String fromUserId) {
    }
}
